package com.cloud.wms.ui.in.presnter;


import android.text.TextUtils;

import com.cloud.core.base.BaseRxPresenter;
import com.cloud.core.http.error.ApiException;
import com.cloud.core.utils.MessageCreator;
import com.cloud.core.utils.TimeUtils;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.http.Params;
import com.cloud.wms.http.observer.LoadingObserver;
import com.cloud.wms.http.observer.ResponseWrapper;
import com.cloud.wms.tools.MemberFun;
import com.cloud.wms.tools.PageHelper;
import com.cloud.wms.tools.RxUtils;
import com.cloud.wms.tools.TaskHelper;
import com.cloud.wms.ui.in.contract.InShelfContract;
import com.cloud.wms.ui.in.entity.InCommodityEntity;
import com.cloud.wms.ui.in.entity.InMarkCommodityEntity;
import com.cloud.wms.ui.in.entity.InMarkEntity;
import com.cloud.wms.ui.in.entity.InOrderEntity;
import com.cloud.wms.ui.main.entity.RemoteEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.main.entity.TitleEntity;
import com.cloud.wms.ui.main.entity.UserEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * @Author:Chen
 * @Date: 2021-01-14 15:51
 * @Description:
 */
public class InShelfPresenter extends BaseRxPresenter<InShelfContract.View> implements InShelfContract.Presenter {
    public static final int IN_TASK = 0x101;
    public static final int IN_ORDER = 0x102;
    public static final int IN_CHECK_MARK_CODE = 0x103;
    public static final int IN_ORDER_DETAIL = 0x104;
    public static final int IN_ORDER_MARK_DETAIL = 0x105;
    public static final int IN_CHECK_COMMODITY_CODE = 0x106;
    public static final int IN_CHECK_POS_CODE = 0x109;
    public static final int IN_MARK_SUBMIT = 0x107;
    public static final int IN_BATCH_SINGLE_SUBMIT = 0x108;
    public static final int CHECK_COMPLETE = 0x110;

    @Inject
    public InShelfPresenter() {

    }

    /**
     * 加载入库单列表
     *
     * @param inCode
     */
    @Override
    public void loadInOrderList(String inCode, int page) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        if (!TextUtils.isEmpty(inCode))
            params.put("InCode", inCode);
        params.put("InStatus", "3");
        FineExApplication
                .component()
                .http()
                .loadInOrderList(params)
                .map(new ResponseWrapper<>())
                .map(new MemberFun<InOrderEntity>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<TitleEntity<InOrderEntity>>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<TitleEntity<InOrderEntity>> info) {
                        if (page == 0) {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEW_DATA));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEXT_DATA));
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                        if (TextUtils.isEmpty(inCode))
                            mView.showError();
                    }
                });
    }

    @Override
    public void receiveShelfTask(InOrderEntity item, String taskCode) {
        TaskHelper.receiveTask(item.getInID() + "", taskCode)
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<TaskEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(TaskEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, IN_TASK));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 箱唛上架加载商品信息
     *
     * @param InID
     * @param isComplete
     */
    @Override
    public void loadInMarkCommodityList(String InID, boolean isComplete) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        //待清点：1，清单完成：2
        params.put("InType", isComplete ? 2 : 1);
        params.put("IsUpBox", true);
        params.put("InID", InID);

        FineExApplication
                .component()
                .http()
                .loadInShelfMarkList(params)
                .map(new ResponseWrapper<>())
                .map(inMarkCommodityEntities -> {
                    ArrayList<TitleEntity<InMarkCommodityEntity.CommodityBean>> list = new ArrayList<>();
                    for (int i = 0; i < inMarkCommodityEntities.size(); i++) {
                        InMarkCommodityEntity entity = inMarkCommodityEntities.get(i);
                        TitleEntity<InMarkCommodityEntity.CommodityBean> titleEntity = new TitleEntity<>();
                        titleEntity.setId(entity.getBoxID());
                        titleEntity.setTitle(entity.getBoxCode());
                        titleEntity.setChildList(entity.getDetailist());
                        list.add(titleEntity);
                    }
                    return list;
                })
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<TitleEntity<InMarkCommodityEntity.CommodityBean>>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<TitleEntity<InMarkCommodityEntity.CommodityBean>> info) {
                        if (info == null || info.isEmpty()) {
                            mView.showEmpty();
                            mView.onSuccess(MessageCreator.createMessage(info, CHECK_COMPLETE));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, IN_ORDER_MARK_DETAIL));
                            mView.showContent();
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                        mView.showError();
                    }
                });
    }

    /**
     * 逐件，批量上架获取商品信息
     *
     * @param InID
     * @param isComplete
     */
    @Override
    public void loadInCommodityList(String InID, boolean isComplete) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        //待清点：1，上架完成：2
        params.put("InType", isComplete ? 2 : 1);
        params.put("IsUpBox", false);
        params.put("InID", InID);

        FineExApplication
                .component()
                .http()
                .loadInShelfCommodityList(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<InCommodityEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<InCommodityEntity> info) {
                        if (info == null || info.isEmpty()) {
                            mView.showEmpty();
                            mView.onSuccess(MessageCreator.createMessage(info, CHECK_COMPLETE));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, IN_ORDER_DETAIL));
                            mView.showContent();
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                        mView.showError();
                    }
                });
    }

    /**
     * 检测上架箱唛号
     *
     * @param InID
     * @param code
     */
    @Override
    public void checkMarkCode(String InID, String code) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        //待清点：1，清单完成：2
        params.put("InputCode", code);
        params.put("IsUpBox", true);
        params.put("InID", InID);

        FineExApplication
                .component()
                .http()
                .checkShelfMarkCode(params)
                .map(new ResponseWrapper<>())
                .flatMap((Function<ArrayList<InMarkEntity>, ObservableSource<InMarkEntity>>) inMarkEntities -> {
                    if (inMarkEntities == null || inMarkEntities.isEmpty()) {
                        return Observable.error(new ApiException("当前入库单不存在箱唛：" + code + "！"));
                    }
                    return Observable.just(inMarkEntities.get(0));
                })
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<InMarkEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(InMarkEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, IN_CHECK_MARK_CODE));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 检测上架商品
     *
     * @param InID
     * @param code
     * @param stockType
     */
    @Override
    public void checkCommodityCode(String InID, String code, int stockType) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        //待清点：1，清单完成：2
        params.put("InputCode", code);
        params.put("IsUpBox", false);
        params.put("InID", InID);

        FineExApplication
                .component()
                .http()
                .checkShelfCommodityCode(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<InCommodityEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(InCommodityEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, IN_CHECK_COMMODITY_CODE));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 检测上架库位
     *
     * @param code
     * @param stockType
     */
    @Override
    public void checkPosCode(String code, int stockType) {
        Params params = Params.newInstance(Params.Type.WAREHOUSE);
        params.put("PosCode", code);
        params.put("StockType", stockType);

        FineExApplication
                .component()
                .http()
                .checkShelfPosCode(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Boolean>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Boolean info) {
                        if (info)
                            mView.onSuccess(MessageCreator.createMessage(code, IN_CHECK_POS_CODE));
                        else
                            mView.info("库位扫描验证失败！");
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 箱唛上架
     *
     * @param taskEntity
     * @param inOrder
     * @param posCode
     * @param markList
     */
    @Override
    public void submitMarkShelf(TaskEntity taskEntity, InOrderEntity inOrder, String posCode, List<InMarkEntity> markList, String beginTime) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        //待清点：1，清单完成：2
        params.put("posCode", posCode);
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < markList.size(); i++) {
            list.add(markList.get(i).getBoxID() + "");
        }
        params.put("boxlist", list);
        params.put("userID", FineExApplication.component().loginCache().getUserInfo().getUserID());

        if (taskEntity == null) {
            params.put("InID", inOrder.getInID());
            params.put("warehouseAreaID", inOrder.getWarehouseAreaID());
            params.put("beginTime", beginTime);
            params.put("completeTime", TimeUtils.getCurrentDateAndTime());
            params.put("workID", 0);
            params.put("appKey", FineExApplication.component().loginCache().getAppKey());
        } else {
            params.put("InID", taskEntity.getBillID());
            params.put("inCode", taskEntity.getBillCode());
            params.put("JobStationID", taskEntity.getJobStationID());
            params.put("ProductCategory", taskEntity.getProductCategory());
            params.put("appKey", taskEntity.getAppKey());
            params.put("workID", taskEntity.getWorkID());
            params.put("warehouseAreaID", taskEntity.getWarehouseAreaID());
        }
        FineExApplication
                .component()
                .http()
                .submitMarkShelfTask(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Object>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Object info) {
                        mView.onSuccess(MessageCreator.createMessage(info, IN_MARK_SUBMIT));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 箱唛上架提交（逐件、批量）
     *
     * @param taskEntity
     * @param inOrder
     * @param commodityList
     */
    @Override
    public void submitSingleAndBatchShelf(TaskEntity taskEntity, InOrderEntity inOrder, List<InCommodityEntity> commodityList, String beginTime) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < commodityList.size(); i++) {
            InCommodityEntity commodityEntity = commodityList.get(i);
            HashMap<String, Object> map = new HashMap<>();
            map.put("commodityID", commodityEntity.getCommodityId());
            map.put("stockType", commodityEntity.getStockType());
            map.put("amount", commodityEntity.getAmount());
            map.put("posCode", commodityEntity.getPosCode());

            ArrayList<HashMap<String, Object>> listBatch = new ArrayList<>();
            HashMap<String, Object> mapBatch = new HashMap<>();
            mapBatch.put("productionDate", commodityEntity.getProductionDate());
            mapBatch.put("expirationDate", commodityEntity.getExpirationDate());
            mapBatch.put("inDate", commodityEntity.getInDate());
            mapBatch.put("productBatchID", commodityEntity.getProductBatchID());
            listBatch.add(mapBatch);
            map.put("batchlist", listBatch);

            list.add(map);
        }
        params.put("list", list);
        params.put("userID", FineExApplication.component().loginCache().getUserInfo().getUserID());

        if (inOrder != null) {
            params.put("workID", 0);
            params.put("InID", inOrder.getInID());
            params.put("warehouseAreaID", inOrder.getWarehouseAreaID());
            params.put("appKey", FineExApplication.component().loginCache().getAppKey());
        } else {
            params.put("InID", taskEntity.getBillID());
            params.put("inCode", taskEntity.getBillCode());
            params.put("taskID", taskEntity.getTaskID());
            params.put("JobStationID", taskEntity.getJobStationID());
            params.put("ProductCategory", taskEntity.getProductCategory());
            params.put("appKey", taskEntity.getAppKey());
            params.put("workID", taskEntity.getWorkID());
            params.put("warehouseAreaID", taskEntity.getWarehouseAreaID());
        }
        params.put("beginTime", beginTime);
        params.put("completeTime", TimeUtils.getCurrentDateAndTime());
        FineExApplication
                .component()
                .http()
                .submitBatchAndSingleShelfTask(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Object>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Object info) {
                        mView.onSuccess(MessageCreator.createMessage(info, IN_BATCH_SINGLE_SUBMIT));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }
}
